package com.rosense.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.rosense.client.rpc.RPCBean;
import com.rosense.client.rpc.RPCIoBean;

/** 
 * 采集磁盘IO使用率 
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年1月23日 下午1:48:32
 * 
 */
public class IoUsage extends ResourceUsage {

	private static IoUsage INSTANCE = new IoUsage();

	private IoUsage() {
	}

	public static IoUsage getInstance() {
		return INSTANCE;
	}

	/** 
	 * @Purpose:采集磁盘IO使用率 
	 * @param args 
	 * @return float,磁盘IO使用率,小于1 
	 */
	@Override
	public RPCBean scan() {
		float ioUsage = 0.0f;
		Process pro = null;
		Runtime r = Runtime.getRuntime();
		RPCIoBean rpc = new RPCIoBean();
		try {
			String command = "iostat -d -x";
			pro = r.exec(command);
			BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			String line = null;
			int count = 0;
			while ((line = in.readLine()) != null) {
				if (++count >= 4) {
					String[] temp = line.split("\\s+");
					if (temp.length > 1) {
						float util = Float.parseFloat(temp[temp.length - 1]);
						ioUsage = Math.max(ioUsage, util);
					}
				}
			}
			rpc.iousage = ioUsage;
			in.close();
			pro.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			String command = "df -l";
			pro = r.exec(command);
			BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			String line = in.readLine();
			while ((line = in.readLine()) != null) {
				String[] temp = line.split("\\s+");
				if (temp.length == 6) {
					try {
						String total = temp[1];
						String used = temp[2];
						String path = temp[5];
						rpc.total += Long.parseLong(total);
						rpc.used += Long.parseLong(used);
						rpc.diskMap.put(path, total + "_" + used);
					} catch (Exception e) {
					}
				}
			}
			in.close();
			pro.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rpc;
	}
}